package com.leoandroid.tool.toolsbox.pedometer.util;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;

import androidx.core.content.ContextCompat;

import com.leoandroid.tool.toolsbox.pedometer.SensorListener;

import java.util.Calendar;

public abstract class Util {

    /**
     * @return milliseconds since 1.1.1970 for today 0:00:00 local timezone
     */
    public static long getToday() {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTimeInMillis();
    }

    /**
     * @return milliseconds since 1.1.1970 for tomorrow 0:00:01 local timezone
     */
    public static long getTomorrow() {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 1);
        c.set(Calendar.MILLISECOND, 0);
        c.add(Calendar.DATE, 1);
        return c.getTimeInMillis();
    }

    /**
     * Android10之后，计步器需要健身运动权限
     *
     * @param context
     * @return
     */
    public static boolean checkRecognitionPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            return ContextCompat.checkSelfPermission(context, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED;
        } else {
            return true;
        }
    }

    public static void startSensorService(Context context) {
        // Create the service connection.
        ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // The binder of the service that returns the instance that is created.
                SensorListener.LocalBinder binder = (SensorListener.LocalBinder) service;

                // The getter method to acquire the service.
                SensorListener binderService = binder.getService();

                // getServiceIntent(context) returns the relative service intent
                startServiceManager(context, true);

                // This is the key: Without waiting Android Framework to call this method
                // inside Service.onCreate(), immediately call here to post the notification.
                binderService.createNotificationChannel(context);
                binderService.showNotification(Integer.MIN_VALUE);

                // Release the connection to prevent leaks.
                context.unbindService(this);
            }

            @Override
            public void onBindingDied(ComponentName name) {
            }

            @Override
            public void onNullBinding(ComponentName name) {
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        };

        // Try to bind the service
        try {
            context.bindService(getServiceIntent(context), connection,
                    Context.BIND_AUTO_CREATE);
        } catch (RuntimeException ignored) {
            // This is probably a broadcast receiver context even though we are calling getApplicationContext().
            // Just call startForegroundService instead since we cannot bind a service to a
            // broadcast receiver context. The service also have to call startForeground in
            // this case.
            startServiceManager(context, false);
        }
    }

    private static Intent getServiceIntent(Context context) {
        return new Intent(context, SensorListener.class);
    }

    private static void startServiceManager(Context context, boolean noNeedShowNotify) {
        try {
            Intent intent = new Intent(context, SensorListener.class);
            intent.putExtra("noNeedShowNotify", noNeedShowNotify);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
